from django.http import HttpResponse, HttpResponseRedirect, Http404
from pollster.models import *

def poll_cookie_key(poll):
	return u'pollster-vote-%s' % poll.id

def has_voted(poll, user, cookies):
	" Returns True if the user has voted on the given Poll. "
	user_voted = user is not None and user.is_authenticated() and poll.vote_set.filter(user=user).count() > 0
	return user_voted or poll_cookie_key(poll) in cookies

def record_vote(choice, request):
	ip_address = request.META.get('REMOTE_ADDR', None)
	vote = Vote(choice=choice, ip_address=ip_address)
	if request.user.is_authenticated():
		vote.user = request.user
	vote.save()
	request.session[poll_cookie_key(choice.poll)] = choice.id

def get_poll(request):
	"""
	Required POST arguments:
		``poll``: ID of the Poll being voted on.
		``choices``: the ID of the Choice voted for.
	"""
	poll_id = request.POST.get('poll', None)
	choice_id = request.POST.get('choices', None)
	if poll_id is None or choice_id is None:
		raise Http404("Both POST parameters `poll` and `choices` were not provided.")
	try:
		poll = Poll.objects.open().get(id=poll_id)
	except Poll.DoesNotExist:
		raise Http404("The poll you are trying to vote on does not exist or is no longer open for voting.")
	try:
		choice = poll.choice_set.get(id=choice_id)
	except Choice.DoesNotExist:
		raise Http404("The choice you are trying to vote on is not valid for this poll.")
	return (poll, choice)
		
def vote(request):
	redirect = request.META.get('HTTP_REFERER', '/')
	if request.method == 'POST':
		poll, choice = get_poll(request)
		if not has_voted(poll, request.user, request.session):
			record_vote(choice, request)
	return HttpResponseRedirect(redirect)
	

def ajax_vote(request):
	poll, choice = get_poll(request)
	if has_voted(poll, request.user, request.session):
		raise Http404("It appears you've already voted on this poll.")
	record_vote(choice, request)
	return HttpResponse("Vote has been recorded.")